<template>
  <el-tabs v-model="activeName" type="card">
    <el-tab-pane label="我负责的" name="first">
      <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="appliedListQuery.searchKey"
        placeholder="名称"
        style="width: 200px"
        class="filter-item"
      />
      <el-select
        v-model="appliedListQuery.sortKey"
        style="width: 140px"
        class="filter-item"
      >
        <el-option
          v-for="item in sortOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="searchAndSort"
      >
        查找
      </el-button>
      <el-button
          v-if="checkPermission(['课题组信息：创建'])"
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          icon="el-icon-edit"
          @click="$router.push(`/researchGroup/create`)"
      >
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="participatedListLoading"
      :data="appliedList"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        label="序列号"
        prop="id"
        sortable="custom"
        align="center"
        width="100"
        :class-name="getSortClass('idNumber')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.idNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课题组名称" min-width="50px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type">{{
            row.researchGroupName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" min-width="50px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type">{{
            row.researchGroupOwnerName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在部门" min-width="50px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type">{{
            row.researchGroupDepartment
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="一级学科" min-width="50px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type">{{
            row.researchGroupSubject
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button
            size="mini"
            type="success"
            @click="$router.push(`/researchGroup/view/${row.id}`)"
          >
            查看
          </el-button>
          <el-button
            v-if="!row.isInProject"
            type="primary"
            size="mini"
            @click="$router.push(`/researchGroup/edit/${row.id}`)"
          >
            编辑
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button
            v-if="!row.isInProject"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="appliedTotal > 0"
      :total="appliedTotal"
      :page.sync="appliedListQuery.pageIndex"
      :limit.sync="appliedListQuery.limit"
      @pagination="getList"
    />
  </div>
</el-tab-pane>
<el-tab-pane label="我参与的" name="second">
      <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="participatedListQuery.searchKey"
        placeholder="名称"
        style="width: 200px"
        class="filter-item"
      />
      <el-select
        v-model="participatedListQuery.sortKey"
        style="width: 140px"
        class="filter-item"
      >
        <el-option
          v-for="item in sortOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="searchAndSortForParticipated"
      >
        查找
      </el-button>
    </div>

    <el-table
      :key="participatedTableKey"
      v-loading="appliedListLoading"
      :data="participatedList"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChangeForParticipated"
    >
      <el-table-column
        label="序列号"
        prop="id"
        sortable="custom"
        align="center"
        width="100"
        :class-name="getSortClassForParticipated('idNumber')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.idNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课题组名称" min-width="50px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type">{{
            row.researchGroupName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" min-width="50px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type">{{
            row.researchGroupOwnerName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在部门" min-width="50px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type">{{
            row.researchGroupDepartment
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="一级学科" min-width="50px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type">{{
            row.researchGroupSubject
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button
            size="mini"
            type="success"
            @click="$router.push(`/researchGroup/view/${row.id}`)"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="participatedTotal > 0"
      :total="participatedTotal"
      :page.sync="participatedListQuery.pageIndex"
      :limit.sync="participatedListQuery.limit"
      @pagination="getList"
    />
  </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { findAll } from "@/utils";
import Pagination from "@/components/Pagination";
import { fetchResearchGroupsByUserId, deleteResearchGroup } from '@/api/research-group';
import { fetchProjectsByGroupId } from "@/api/project";
import { mapGetters } from "vuex";
import { checkPermission, checkUserPermission } from '@/utils/permission'

export default {
  name: "myGroupList",
  components: { Pagination },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  data() {
    return {
      tableKey: 0,
      participatedTableKey: 0,
      totalAppliedList: null,
      totalParticipatedList: null,
      appliedList: null,
      participatedList: null,
      appliedTotal: 0,
      participatedTotal: 0,
      appliedListLoading: true,
      participatedListLoading: true,
      activeName: 'first',
      appliedListQuery: {
        pageIndex: 1,
        limit: 10,
        searchField: 'researchGroupName',
        searchKey: '',
        sortField: 'idNumber',
        sortKey: "asce",
      },
      participatedListQuery: {
        pageIndex: 1,
        limit: 10,
        searchField: 'researchGroupName',
        searchKey: '',
        sortField: 'idNumber',
        sortKey: "asce",
      },
      sortOptions: [
        { label: "序列号 升序", key: "asce" },
        { label: "序列号 降序", key: "desc" },
      ]
    };
  },
  computed: {
    ...mapGetters(["id", "name", "roles"])
  },
  created() {
    this.getList();
  },
  methods: {
    checkPermission,
    getList() {
      this.appliedListLoading = true;
      this.participatedListLoading = true;
      fetchResearchGroupsByUserId(this.id).then((res) => {
        this.totalAppliedList = res.data.applied.map((item, index) => {
          item.idNumber = index + 1;
          return item;
        });
        this.totalAppliedList.forEach(element => {
          fetchProjectsByGroupId(element.id).then((result) => {
            if (result && result.data.length > 0) {
              element.isInProject = true
            } else {
              element.isInProject = false
            }
        });
      });
        this.totalParticipatedList = res.data.participated.map((item, index) => {
          item.idNumber = index + 1;
          return item;
        });
        this.handleFilter();
        this.handleParticipatedFilter();

        this.appliedListLoading = false;
        this.participatedListLoading = false;
      });
    },
    handleFilter() {
      const result=findAll(this.totalAppliedList, this.appliedListQuery);
      this.appliedList = result.data;
      this.appliedTotal=result.total;
    },
    handleParticipatedFilter() {
      const result=findAll(this.totalParticipatedList, this.participatedListQuery);
      this.participatedList = result.data;
      this.participatedTotal=result.total;
    },
    searchAndSort() {
      this.appliedListQuery.pageIndex = 1;
      this.handleFilter();
    },
    searchAndSortForParticipated() {
      this.participatedListQuery.pageIndex = 1;
      this.handleParticipatedFilter();
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortChangeForParticipated(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByIDForParticipated(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.appliedListQuery.sortKey = "asce";
      } else {
        this.appliedListQuery.sortKey = "desc";
      }
      this.appliedListQuery.pageIndex = 1;
      this.handleFilter();
    },
    sortByIDForParticipated(order) {
      if (order === "ascending") {
        this.participatedListQuery.sortKey = "asce";
      } else {
        this.participatedListQuery.sortKey = "desc";
      }
      this.participatedListQuery.pageIndex = 1;
      this.handleParticipatedFilter();
    },
    handleDelete(row, index) {
      this.$confirm(`是否确定删除 "${row.researchGroupName}"`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        //请求接口
        deleteResearchGroup(row.id)
          .then((res) => {
            if (res.data) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              //重新获取
              this.getList();
            } else {
              this.$message({
                message: "项目删除失败",
                type: "error",
              });
            }
          })
          .catch((err) => {
            this.$message({
              message: "项目删除失败",
              type: "error",
            });
          });
      });
    },
    getSortClass: function (key) {
      const sort = this.appliedListQuery.sortKey;
      return sort === `asce` ? "ascending" : "descending";
    },
    getSortClassForParticipated: function (key) {
      const sort = this.participatedListQuery.sortKey;
      return sort === `asce` ? "ascending" : "descending";
    },
  },
};
</script>
